import BaseLayer from './baseLayer';
import CityLayerGroup from './city';
import { compare } from './common';
export default class ProvinceNcovLayer extends BaseLayer {
  addLayerEvent() {
    // 左键双击dblclick，下钻
    this.layers[0].on('click', e => {
      // 下钻城市地图
      // console.log(e, "123");
      const { adcode, name, count, cities = [] } = e.feature.properties;
      // console.log("点击省份***", name, adcode);
      if (!count) {
        // console.log("很抱歉，当前省份下无数据~");
        return;
      }
      this.addCityLayer(adcode, cities, name);
    });
  }
  async addCityLayer(adcode, citydata, name) {
    // 城市GEO数据:adcode
    const cityGeo = await (
      await fetch(`https://gw.alipayobjects.com/os/antvdemo/assets/json/${adcode}.json`)
    ).json();
    // console.log(cityGeo, "当前省份下的geo数据");
    const dataPoint = cityGeo.features.map(fe => {
      return {
        adcode: fe.properties.adcode,
        name: fe.properties.name,
        center: fe.properties.centroid || fe.properties.center,
      };
    });
    const cityTop10 = [];
    cityGeo.features = cityGeo.features.map(fe => {
      const adcode = fe.properties.adcode;
      const city = citydata.find(c => {
        // 名称匹配
        // if (c.name === "恩施州") c.name = "恩施";
        // if (name.match(c.name) !== null || c.name.match(name) !== null) {
        // console.log("根据name匹配成功，返回-->当前省份下城市--业务数据", c);
        //   return true;
        // }
        // 编码adcode匹配
        if (c.adcode && adcode && adcode === c.adcode) {
          // console.log("根据adcode匹配成功，返回-->当前省份下城市--业务数据", c);
          return true;
        }
        return false;
      });

      // 业务数据相关
      if (city) {
        fe.properties.count = city.count || 0;
        cityTop10.push({
          adcode: city.adcode,
          name: city.name,
          count: city.count,
        });
      } else {
        fe.properties.count = 0;
      }
      return fe;
    });

    // 左侧info：全国>省份
    const info = this.scene.getControlByName('infoControl');
    if (!info) {
      return;
    }

    // 排名
    cityTop10.sort(compare('count'));
    const mapInfo = this.scene.getControlByName('mapInfoControl');
    if (!mapInfo) {
      return;
    }

    this.cityLayer = new CityLayerGroup(
      this.scene,
      cityGeo,
      dataPoint,
      cityTop10 // 地图颜色根据排名展示
    );

    // 城市图层，空白处点击-返回全国地图
    this.cityLayer.layers[0].on('undblclick', () => {
      this.cityLayer.destroy();
      this.show();
      this.scene.render();
      info.update();
      mapInfo.update(this.provinceTop10);
    });

    // 下钻后，隐藏省份地图，展示城市地图
    this.hide();
    setTimeout(() => {
      this.scene.render();
      info.update(name);
      console.log('当前城市前10名：', cityTop10);
      mapInfo.update(cityTop10);
    }, 10);
  }
}
